package com.winsomely.leecode;

import java.util.HashSet;
import java.util.Set;
import java.util.stream.Stream;

/**
 * 两个数组的交集
 * 
 * @author liujiawei
 *
 */
public class Intersection {

	public int[] intersection(int[] nums1, int[] nums2) {
		Set<Integer> set = new HashSet<>();
		int[] temp = nums1.length < nums2.length ? nums1 : nums2;
		for (int i = 0; i < temp.length; i++) {
			if (!set.contains(temp[i])) {
				set.add(temp[i]);
			}
		}
		int[] temp2 = nums1.length >= nums2.length ? nums1 : nums2;
		Set<Integer> set2 = new HashSet<>();
		for (int i = 0; i < temp2.length; i++) {
			if (set.contains(temp2[i])) {
				set2.add(temp2[i]);
			}
		}
		int[] result = new int[set2.size()];
		Object[] oList = set2.toArray();
		Stream.iterate(0, i -> i + 1).limit(set2.size()).forEach(i -> result[i] = (Integer) oList[i]);

		return result;
	}

	public static void main(String[] args) {
		int[] nums1 = { 1, 2, 2, 3, 3, 4, 5 };
		int[] nums2 = { 2, 2, 3, 3 };
		Intersection t = new Intersection();
		int[] r = t.intersection(nums1, nums2);
		for (int k = 0; k < r.length; k++) {
			System.out.print(r[k] + ", ");
		}
	}

}
